/**
 * 
 */
package uy.com.pzit.fpmundialmodel.dao;

import java.util.List;

import net.sf.ehcache.ObjectExistsException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBObject;
import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBTemplate;
import uy.com.pzit.fpmundialmodel.domain.Mundial;

/**
 * @author pferraz
 * 
 */
public class MundialDAO {

	private static Logger logger = Logger.getLogger(MundialDAO.class);

	public Mundial addMundial(Mundial mundial) {
		return (DBObject.addObject(mundial)) ? mundial : null;
	}

	public Mundial getMundialById(Integer id) {
		return (Mundial) DBObject.getObjectById(Mundial.class, id);
	}

	public Mundial updateMundial(Mundial mundial) {
		return (DBObject.updateObject(mundial)) ? mundial : null;
	}

	@SuppressWarnings("unchecked")
	public Mundial getLastMundial() {
		Session sess = null;
		Mundial result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory()
					.openSession();

			Query query = sess
					.createQuery("from m in class uy.com.pzit.fpmundialmodel.domain.Mundial where m.id =" +
							" (Select max(mund.id) FROM uy.com.pzit.fpmundialmodel.domain.Mundial mund)");

			List<Mundial> list = query.list();
			if (list.isEmpty()) {
				throw new ObjectExistsException("No existen paises.");
			} else {
				result = list.get(0);
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar mundiales", e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result;
	}

	public boolean checkMundialEnCurso() {
		Session sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
		int count = ((Long)sess.createQuery("select count(*) from Mundial m where m.fechaFin IS NULL").uniqueResult()).intValue();
		if (sess != null) {
			sess.close();
		}
		return count>0;
	}

}
